package com.snow.vpnclient.api;

import java.io.IOException;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author liufq
 * @since 2023-01-05 10:40:37
 */
public class DomainSwitchInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        return chain.proceed(buildRequest(chain));
    }

    /**
     * 构建新的服务器地址
     *
     * @param chain
     * @return
     */
    public Request buildRequest(Chain chain) {
        Request request = chain.request();
        HttpUrl httpUrl = request.url();
        String domain = request.header("domain");
        if (domain != null && domain.length() > 0) {
            //替换服务器
            HttpUrl domainUrl = HttpUrl.parse(domain);
            HttpUrl newUrl = httpUrl.newBuilder().scheme(domainUrl.scheme()).host(domainUrl.host()).port(domainUrl.port()).build();
            //构建新的请求方式
            Request.Builder builder = request.newBuilder();
            builder.url(newUrl);
            request = builder.build();
        }
        return request;
    }
}
